# -*- coding: utf-8 -*-
# @name             : 认证服务
# @author           : OneYoung
# @create           : 2024/07/18
# @version          : v1.0
# @desc             :

import requests
from utils.log_record import logger
from utils.redis_getter import RedisGetter
from application.settings import BASE_URL, TIMEOUT


# 处理认证token
class AuthToken:

    @staticmethod
    def update():
        """更新token"""
        url = BASE_URL + '/token'
        headers = {"content-type": "application/x-www-form-urlencoded"}

        body = {
            "username": "tester",
            "password": "Test@123456"
        }
        response = requests.post(url, headers=headers, data=body, timeout=TIMEOUT)
        if response.status_code == 200:
            try:
                access_token = response.json()['access_token']
                # 缓存token,有效期1小时,根据实际调整
                RedisGetter().set('access_token', access_token, 3600)
                return access_token
            except Exception as e:
                logger.error(f"认证失败，{e}")
        logger.error("认证失败，请检查服务及认证信息...")
        return None

    @classmethod
    def get(cls):
        """获取授权token"""
        token = RedisGetter().get('access_token')
        if not token:
            token = cls.update()
        return token
